package com.huawei.bitfun.listener;

import com.huawei.bitfun.ConfigProvider;
import com.huawei.bitfun.Constants;
import com.huawei.bitfun.OptimizeManager;
import com.huawei.bitfun.bean.DocumentBean;
import com.huawei.bitfun.helper.YamlParser;
import com.huawei.deveco.projectmodel.ohos.model.ProjectModel;
import com.huawei.deveco.projectmodel.ohos.sync.syncinterface.ProjectSetUp;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.vfs.*;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class OptProjectSetup implements ProjectSetUp, Disposable {
    @Override
    public void projectSetUp(@NotNull ProjectModel projectModel) {
        ConfigProvider.getInstance().setProject(projectModel.getProject());
        updateOptYmlFileBeans();
        addOptYmlFileListener();
    }

    @Override
    public void dispose() {}

    private void addOptYmlFileListener() {
        var optYmlFileListener = new OptYmlFileListener();
        ApplicationManager.getApplication()
                .getMessageBus()
                .connect()
                .subscribe(VirtualFileManager.VFS_CHANGES, optYmlFileListener);
    }

    private void updateOptYmlFileBeans() {
        var optYmlFiles = findOptYmlFiles();
        optYmlFiles.forEach(file -> {
            var module = ConfigProvider.getInstance().getModuleModel(file);
            if (module == null || !module.isNativeModule()) {
                return;
            }
            List<DocumentBean> documentBeans = YamlParser.parserOptYml(file, module);
            OptimizeManager.getInstance().addAllDocumentBean(documentBeans);
        });
    }

    private List<VirtualFile> findOptYmlFiles() {
        List<VirtualFile> optYmlFiles = new ArrayList<>();
        var nativeModules = ConfigProvider.getInstance().getNativeModules();
        Consumer<VirtualFile> addOptYmlFiles = (optFile) -> VfsUtilCore.visitChildrenRecursively(optFile, new VirtualFileVisitor<Void>() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {
                var name = file.getName();
                var path = file.getCanonicalPath();
                if (path == null) {
                    return super.visitFile(file);
                }
                if (name.endsWith(Constants.FILE_SUFFIX) && path.contains(Constants.TEMP_DIR_NAME)) {
                    optYmlFiles.add(file);
                }
                return super.visitFile(file);
            }
        });
        nativeModules.forEach(module -> {
            var moduleVFile = LocalFileSystem.getInstance().findFileByPath(module.getModulePath());
            addOptYmlFiles.accept(moduleVFile);
        });
        return optYmlFiles;
    }
}